package handler

import (
	"github.com/gin-gonic/gin"
	"honghu_be/common"
	"honghu_be/dal"
	"honghu_be/model"
	"honghu_be/model/vo"
)

func GetArticles(c *gin.Context) {
	req := &model.GetArticlesRequest{}
	if err := c.ShouldBind(req); err != nil {
		c.JSON(400, err.Error())
		return
	}
	resp, err := getArticles(c, req)
	if err != nil {
		common.WriteError(c, err)
		return
	}
	c.JSON(200, resp)
}

func getArticles(c *gin.Context, req *model.GetArticlesRequest) (*model.GetArticlesResponse, error) {
	pos, err := dal.GetArticles(c, &dal.GetArticlesRequest{
		Limit:  req.Limit,
		Offset: req.Offset,
	})
	if err != nil {
		return nil, err
	}
	return &model.GetArticlesResponse{
		Meta:     common.MetaOk,
		Articles: vo.ToArticleVos(pos),
	}, nil
}
